<template>
  <el-dialog
    :model-value="visible"
    :title="modalTitle"
    width="700px"
    :before-close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="商品标题" prop="title">
        <el-input
          v-model="formState.title"
          placeholder="请输入商品标题"
          :maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="商品描述" prop="description">
        <el-input
          v-model="formState.description"
          type="textarea"
          placeholder="请输入商品描述"
          :rows="4"
          :maxlength="255"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品分类" prop="category">
            <el-select
              v-model="formState.category"
              placeholder="请选择商品分类"
              style="width: 100%"
            >
              <el-option label="电子产品" value="电子产品" />
              <el-option label="学习用品" value="学习用品" />
              <el-option label="生活用品" value="生活用品" />
              <el-option label="服装鞋帽" value="服装鞋帽" />
              <el-option label="图书资料" value="图书资料" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品价格" prop="price">
            <el-input-number
              v-model="formState.price"
              placeholder="请输入商品价格"
              :min="0"
              :precision="2"
              style="width: 100%"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="商品图片" prop="images">
        <!-- 完全自定义上传实现 -->
        <div class="upload-container">
          <div class="upload-area" @click="triggerFileInput" v-if="uploadedImages.length + uploadingFiles.length < 5">
            <el-icon size="24" class="upload-icon"><Plus /></el-icon>
            <div class="upload-text">点击上传图片</div>
            <div class="upload-subtext">最多可上传5张图片</div>
          </div>
          
          <input
            ref="fileInputRef"
            type="file"
            multiple
            accept=".jpg,.jpeg,.png,.webp"
            style="display: none"
            @change="handleFileSelect"
          />

          <!-- 图片预览区域 -->
          <div class="image-preview-container" v-if="uploadedImages.length > 0 || uploadingFiles.length > 0">
            <div class="preview-title">已上传图片 ({{ uploadedImages.length }}/5)</div>
            <div class="image-preview-list">
              <!-- 已上传的图片 -->
              <div
                v-for="(image, index) in uploadedImages"
                :key="'uploaded-' + index"
                class="image-preview-item"
              >
                <img :src="getFullImageUrl(image)" :alt="'图片' + (index + 1)" @error="handleImageError" />
                <div class="image-actions">
                  <el-tooltip content="预览" placement="top">
                    <el-icon class="preview-btn" @click="handlePreview(getFullImageUrl(image))"><View /></el-icon>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-icon class="delete-btn" @click="handleDeleteImage(image)"><Delete /></el-icon>
                  </el-tooltip>
                </div>
                <div class="image-index">{{ index + 1 }}</div>
              </div>
              
              <!-- 上传中的图片 -->
              <div
                v-for="(file, index) in uploadingFiles"
                :key="'uploading-' + index"
                class="image-preview-item uploading"
              >
                <div class="uploading-overlay">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <div>上传中...</div>
                  <div class="file-name">{{ getShortFileName(file.file.name) }}</div>
                </div>
                <img :src="file.previewUrl" :alt="file.file.name" />
                <div class="image-index">上传中</div>
              </div>

              <!-- 空白占位，用于对齐 -->
              <div
                v-for="i in (5 - uploadedImages.length - uploadingFiles.length)"
                :key="'empty-' + i"
                class="image-preview-item empty"
              >
                <div class="empty-slot">
                  <el-icon><Plus /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <div class="upload-tip">支持 JPG、PNG、WebP 格式，单张图片不超过 2MB</div>
          
          <div v-if="uploadError" class="upload-error">
            {{ uploadError }}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="联系方式" prop="contact_info">
        <el-input
          v-model="formState.contact_info"
          placeholder="请输入联系方式（电话/微信等）"
          :maxlength="255"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          :loading="confirmLoading" 
          @click="handleOk"
          :disabled="uploadedImages.length === 0"
        >
          {{ confirmLoading ? '提交中...' : '确认' }}
        </el-button>
      </span>
    </template>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="60%"
      align-center
    >
      <div class="preview-dialog-content">
        <img :src="previewImage" class="preview-image" alt="预览" />
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, View, Delete, Loading } from '@element-plus/icons-vue';
import { goodApi } from '@/api/good';
import { uploadGoodImage, deleteGoodImage } from '@/api/upload';

const props = defineProps({
  visible: Boolean,
  good: Object,
  mode: String // 'create' | 'edit'
});

const emit = defineEmits(['cancel', 'ok']);

const formRef = ref();
const fileInputRef = ref();
const confirmLoading = ref(false);
const previewVisible = ref(false);
const previewImage = ref('');
const uploadError = ref('');

// 自定义状态管理
const uploadedImages = ref([]); // 存储已成功上传的图片URL
const uploadingFiles = ref([]); // 存储正在上传的文件

// 表单状态
const formState = reactive({
  title: '',
  description: '',
  category: '',
  price: undefined,
  images: '', // 存储为字符串
  contact_info: ''
});

// 计算属性
const uploadedCount = computed(() => uploadedImages.value.length);
const uploadingCount = computed(() => uploadingFiles.value.length);

// 获取完整的图片URL
const getFullImageUrl = (url) => {
  if (!url) return '';
  
  // 如果已经是完整URL，直接返回
  if (url.startsWith('http') || url.startsWith('//')) {
    return url;
  }
  
  // 如果是相对路径，添加基础URL
  if (url.startsWith('/')) {
    // 这里需要根据你的实际配置设置基础URL
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
    return `${baseUrl}${url}`;
  }
  
  // 如果是以 public/uploads 开头的路径
  if (url.includes('public/uploads')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
    return `${baseUrl}${url.startsWith('/') ? '' : '/'}${url}`;
  }
  
  return url;
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  event.target.src = '/placeholder-image.jpg'; // 可以设置一个默认图片
};

// 获取短文件名
const getShortFileName = (filename) => {
  if (filename.length <= 10) return filename;
  return filename.substring(0, 8) + '...' + filename.split('.').pop();
};

// 自定义图片验证规则
const validateImages = (rule, value, callback) => {
  console.log('验证图片，当前值:', value, '已上传图片:', uploadedImages.value);
  
  if (uploadedImages.value.length === 0) {
    callback(new Error('请至少上传一张商品图片'));
  } else {
    callback();
  }
};

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { max: 255, message: '描述不能超过255个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  images: [
    { validator: validateImages, trigger: 'change' }
  ],
  contact_info: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { max: 255, message: '联系方式不能超过255个字符', trigger: 'blur' }
  ]
};

// 模态框标题
const modalTitle = computed(() => {
  return props.mode === 'create' ? '发布二手商品' : '编辑商品信息';
});

// 触发文件选择
const triggerFileInput = () => {
  if (uploadedImages.value.length + uploadingFiles.value.length >= 5) {
    ElMessage.warning('最多只能上传5张图片');
    return;
  }
  fileInputRef.value?.click();
};

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files);
  console.log('选择的文件:', files);
  
  if (files.length === 0) return;
  
  // 检查总数量
  const totalFiles = uploadedImages.value.length + uploadingFiles.value.length + files.length;
  if (totalFiles > 5) {
    ElMessage.warning('最多只能上传5张图片，已自动过滤多余图片');
    // 只取前几个文件
    files.splice(5 - (uploadedImages.value.length + uploadingFiles.value.length));
  }
  
  // 处理每个文件
  files.forEach(file => {
    handleFileUpload(file);
  });
  
  // 清空input值，允许重复选择相同文件
  event.target.value = '';
};

// 处理单个文件上传
const handleFileUpload = async (file) => {
  console.log('开始处理文件上传:', file.name);
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG、PNG、WebP 格式的图片!');
    return;
  }
  
  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return;
  }

  // 创建预览URL
  const previewUrl = URL.createObjectURL(file);
  
  // 创建上传记录
  const uploadRecord = {
    id: Date.now() + Math.random().toString(36).substr(2, 9),
    file: file,
    previewUrl: previewUrl,
    status: 'uploading'
  };

  // 添加到上传中列表
  uploadingFiles.value.push(uploadRecord);

  try {
    console.log('开始上传到服务器:', file.name, '大小:', file.size);
    
    // 上传到服务器
    const response = await uploadGoodImage(file);
    console.log('上传接口响应:', response);
    
    if (response.code === 0) {
      // 上传成功
      const serverUrl = response.data.url;
      
      // 从上传中列表移除
      uploadingFiles.value = uploadingFiles.value.filter(item => item.id !== uploadRecord.id);
      
      // 添加到已上传列表
      uploadedImages.value.push(serverUrl);
      
      // 更新表单数据
      updateFormImages();
      
      ElMessage.success('图片上传成功');
      console.log('图片上传成功，服务器URL:', serverUrl);
      
      // 手动触发表单验证
      nextTick(() => {
        formRef.value?.validateField('images');
      });
    } else {
      // 上传失败
      handleUploadError(uploadRecord.id, response.msg || '上传失败');
    }
  } catch (error) {
    // 上传失败
    handleUploadError(uploadRecord.id, error.message || '上传失败');
  }
};

// 处理上传错误
const handleUploadError = (fileId, errorMsg) => {
  console.error('上传失败:', fileId, errorMsg);
  
  // 从上传中列表移除
  const failedFile = uploadingFiles.value.find(item => item.id === fileId);
  if (failedFile) {
    // 释放blob URL
    URL.revokeObjectURL(failedFile.previewUrl);
  }
  
  uploadingFiles.value = uploadingFiles.value.filter(item => item.id !== fileId);
  uploadError.value = errorMsg;
  ElMessage.error(errorMsg);
  
  // 3秒后清空错误信息
  setTimeout(() => {
    uploadError.value = '';
  }, 3000);
};

// 更新表单图片数据
const updateFormImages = () => {
  formState.images = uploadedImages.value.join(',');
  console.log('更新表单图片数据:', formState.images);
};

// 删除图片
const handleDeleteImage = async (imageUrl) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
      type: 'warning'
    });
    
    // 从已上传列表中移除
    uploadedImages.value = uploadedImages.value.filter(url => url !== imageUrl);
    
    // 更新表单数据
    updateFormImages();
    
    // 删除服务器上的文件
    try {
      await deleteGoodImage(imageUrl);
      console.log('服务器图片删除成功');
    } catch (error) {
      console.error('删除服务器图片失败:', error);
      // 不阻止删除，只是记录错误
    }
    
    // 手动触发表单验证
    nextTick(() => {
      formRef.value?.validateField('images');
    });
    
    ElMessage.success('图片删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error);
    }
  }
};

// 图片预览
const handlePreview = (imageUrl) => {
  previewImage.value = imageUrl;
  previewVisible.value = true;
};

// 监听商品数据变化
watch(
  () => props.good,
  (newGood) => {
    console.log('接收到商品数据:', newGood);
    console.log('当前模式:', props.mode);
    
    if (newGood && props.mode === 'edit') {
      console.log('价格字段原始值:', newGood.price);
      console.log('价格字段转换后:', Number(newGood.price));
      
      // 重置状态
      resetForm();
      
      // 填充数据
      Object.keys(formState).forEach(key => {
        if (newGood[key] !== undefined && newGood[key] !== null) {
          // 特殊处理价格字段
          if (key === 'price') {
            formState[key] = Number(newGood[key]);
          } else {
            formState[key] = newGood[key];
          }
        }
      });

      // 处理图片数据
      let imageUrls = [];
      
      if (newGood.images) {
        if (Array.isArray(newGood.images)) {
          imageUrls = newGood.images.filter(url => url && url.trim());
        } else if (typeof newGood.images === 'string') {
          if (newGood.images.includes(',')) {
            imageUrls = newGood.images.split(',').filter(url => url && url.trim());
          } else if (newGood.images.trim()) {
            imageUrls = [newGood.images.trim()];
          }
        }
      }
      
      // 设置已上传图片
      uploadedImages.value = imageUrls;
      updateFormImages();

      console.log('编辑模式初始化数据:', {
        formState: { ...formState },
        uploadedImages: uploadedImages.value
      });
    }
  },
  { immediate: true }
);

// 监听可见性变化
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      resetForm();
    } else {
      // 模态框打开时，如果有图片，触发验证
      if (uploadedImages.value.length > 0) {
        nextTick(() => {
          formRef.value?.validateField('images');
        });
      }
    }
  }
);

// 重置表单
const resetForm = () => {
  // 清理所有blob URL
  uploadingFiles.value.forEach(item => {
    if (item.previewUrl && item.previewUrl.startsWith('blob:')) {
      URL.revokeObjectURL(item.previewUrl);
    }
  });
  
  formRef.value?.resetFields();
  uploadedImages.value = [];
  uploadingFiles.value = [];
  uploadError.value = '';
  
  // 重置表单状态 - 确保价格字段正确重置
  Object.keys(formState).forEach(key => {
    if (key === 'price') {
      formState[key] = undefined; // 对于 el-input-number，使用 undefined 而不是空字符串
    } else {
      formState[key] = '';
    }
  });
  
  console.log('表单已重置', { ...formState });
};

// 确认操作
const handleOk = async () => {
  try {
    console.log('开始提交表单验证');
    console.log('已上传图片:', uploadedImages.value);
    console.log('上传中文件:', uploadingFiles.value);
    
    // 检查是否有正在上传的文件
    if (uploadingFiles.value.length > 0) {
      ElMessage.warning('请等待图片上传完成');
      return;
    }
    
    // 检查图片数量
    if (uploadedImages.value.length === 0) {
      ElMessage.error('请至少上传一张商品图片');
      return;
    }

    // 验证表单
    await formRef.value.validate();
    
    confirmLoading.value = true;
    
    // 准备提交数据
    const submitData = {
      ...formState,
      price: Number(formState.price),
      images: formState.images
    };
    
    console.log('提交的商品数据:', submitData);
    
    let response;
    if (props.mode === 'create') {
      response = await goodApi.create(submitData);
    } else {
      response = await goodApi.update(props.good.item_id, submitData);
    }

    console.log('商品API响应:', response);

    if (response.code === 0) {
      ElMessage.success(props.mode === 'create' ? '发布成功' : '更新成功');
      emit('ok');
    } else {
      ElMessage.error(response.msg || '操作失败');
    }
  } catch (error) {
    console.error('商品操作失败:', error);
    if (error.fields) {
      ElMessage.error('请完善表单信息');
    } else {
      ElMessage.error('网络错误，请重试');
    }
  } finally {
    confirmLoading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  resetForm();
  emit('cancel');
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-container {
  width: 100%;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
  margin-bottom: 16px;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.upload-icon {
  color: #c0c4cc;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.upload-subtext {
  color: #909399;
  font-size: 12px;
}

.image-preview-container {
  margin-bottom: 16px;
}

.preview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  font-weight: 500;
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.image-preview-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  background: #f5f7fa;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview-item:hover .image-actions {
  opacity: 1;
}

.preview-btn,
.delete-btn {
  color: white;
  font-size: 18px;
  margin: 0 8px;
  cursor: pointer;
  transition: color 0.3s;
}

.preview-btn:hover {
  color: #409eff;
}

.delete-btn:hover {
  color: #f56c6c;
}

.image-index {
  position: absolute;
  top: 4px;
  left: 4px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
}

.uploading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 12px;
  z-index: 2;
}

.loading-icon {
  animation: rotating 2s linear infinite;
  margin-bottom: 4px;
  color: #409eff;
}

.file-name {
  margin-top: 4px;
  font-size: 10px;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 24px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.upload-error {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 8px;
  padding: 8px;
  background: #fef0f0;
  border-radius: 4px;
  border: 1px solid #fbc4c4;
}

.preview-dialog-content {
  text-align: center;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>